package net.hanjava.roas;

import java.io.IOException;
import java.io.InputStream;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

public class XlsResourceSheet implements ResourceSheet {
	private XlsBook workbook;

	private String[][] table = null;

	private String name;

	public XlsResourceSheet(XlsBook book, int sheetIndex) {
		this.workbook = book;
		xls2table(workbook.getWorkbook(), sheetIndex);
	}

	public XlsResourceSheet(InputStream source) {
		this(source, 0);
	}

	public XlsResourceSheet(InputStream source, int sheetIndex) {
		POIFSFileSystem fs = null;
		try {
			fs = new POIFSFileSystem(source);
			HSSFWorkbook book = new HSSFWorkbook(fs);
			xls2table(book, sheetIndex);
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	@SuppressWarnings("deprecation")
	private void xls2table(HSSFWorkbook book, int sheetIndex) {
		HSSFSheet sheet = book.getSheetAt(sheetIndex);
		this.name = book.getSheetName(sheetIndex);
		int lastRowIndex = sheet.getLastRowNum();
		HSSFRow row0 = sheet.getRow(0); // row for locale keys
		if (row0 == null)
			return;
		int lastColIndex = findLastCol(row0);
		table = new String[lastRowIndex + 1][lastColIndex + 1];
		for (int rIndex = 0; rIndex <= lastRowIndex; rIndex++) {
			HSSFRow r = sheet.getRow(rIndex);
			for (short cIndex = 0; cIndex <= lastColIndex; cIndex++) {
				HSSFCell c = r.getCell(cIndex);
				String v = c == null ? "" : c.getStringCellValue();
				table[rIndex][cIndex] = v;
			}
		}
	}

	@SuppressWarnings("deprecation")
	private int findLastCol(HSSFRow row0) {
		short lastColIndex = (short) (row0.getLastCellNum() - 1);
		// search non-empty column from the last
		short curCol = lastColIndex;
		while (curCol > 1) { // first column must be a resource keys
			HSSFCell cell = row0.getCell(curCol);
			if (cell != null) {
				// uses deprecated method for performance
				String v = cell.getStringCellValue();
				if (v != null & v.length() > 0)
					return curCol;
			}
			curCol--;
		}
		return 0;
	}

	public String get(int row, int col) {
		return table[row][col];
	}

	public int getColumnCount() {
		return table[0].length;
	}

	public int getRowCount() {
		if (table == null)
			return -1;
		return table.length;
	}

	public String getName() {
		return name;
	}
}